﻿using CUGroup.IOT.Unit.Helper;
using CUGroup.IOT.Unit.Ilog;
using iot.Jobs;
using iot.Jobs.Entity;
using iot.Models;
using Microsoft.IdentityModel.Tokens;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CUGroup.IOT.Win.Winform
{
    internal class PlcDataCollectionJob : IJob
    {
        SeriLogHelper.Logger connectionLoggera = new SeriLogHelper.Logger("PLC_data_ssDa");

        public async Task Execute(IJobExecutionContext context)
        {
            var currentFireTime = context.FireTimeUtc;
            var plcInfo = context.MergedJobDataMap["cinfos"] as List<PlcInfo>;
            if (plcInfo != null)
            {
                try
                {
                    await CollectDataFromPlc_new(plcInfo, context, currentFireTime);
                }
                catch (Exception)
                {
                    // Log or handle the exception here if needed
                    throw;
                }
            }
        }

        /// <summary>
        /// 20250401
        /// </summary>
        /// <param name="pointInfos"></param>
        /// <param name="cinfos"></param>
        /// <param name="driverLoader"></param>
        /// <returns></returns>
        private async Task CollectDataFromPlc_new(
            List<PlcInfo> cinfos,
            IJobExecutionContext context = null, DateTimeOffset currentFireTime = default)
        {
            foreach (var item in cinfos)
            {
                _ = ThreadPool.QueueUserWorkItem(state =>
                {
                    if (state is PlcInfo plcInfo) // Ensure the state is not null and is of type PlcInfo
                    {
                        // 在后台线程中执行耗时操作
                        try
                        {
                            PutKafkaData putKafkaData = new PutKafkaData();
                            putKafkaData.Name = "Sample data for Kafka"; // 替换为实际数据
                            putKafkaData.Group = "SampleGroup"; // 替换为实际分组
                            putKafkaData.ThreadId = Thread.CurrentThread.ManagedThreadId.ToString(); // 获取当前线程ID
                            GlobalQueue.Queue.Add(putKafkaData);
                            connectionLoggera.AppendLog($"PutKafkaDataJob executed at {DateTime.Now}. Data added to queue: {plcInfo.IP}");
                        }
                        catch (Exception ex)
                        {
                            // 处理异常
                            connectionLoggera.AppendLog($"PutKafkaDataJob executed at {DateTime.Now}. Data added to queue: {ex.Message}");
                        }
                    }
                    else
                    {
                        connectionLoggera.AppendLog($"PutKafkaDataJob executed at {DateTime.Now}. Data added to queue: 异常");
                    }
                }, item);
            }
        }
    }
}
